import React from 'react';
import {Menu, Dropdown, Input, Button, Table, Modal, Select, message, Form,} from 'antd';
import { DownOutlined, EditOutlined, MinusCircleOutlined} from '@ant-design/icons';
import './DepAndStaffUserAccount.css';
// import axios from "axios";
import axios from '../../util/http'
import * as url from '../../util/api'

const { Search } = Input;
const { Option } = Select;

class DepAndStaffUserAccount extends React.Component {
    constructor(props){
        super(props);
        this.state={
            currentPage: 1,    //当前页
            perSize: 5,    //页容量
            totalCounts: '',    //总条数
            allState:[    //全部状态
                {key:'22',name:'全部状态'},
                {key:'0',name:'启用'},
                {key:'1',name:'禁用'},
                ],
            allDept:[    //全部部门
                /*{deptId:'1',deptName:'财务部'},
                {deptId:'2',deptName:'销售部'},*/
                ],
            allJob:[    //全部职位
               /* {jobId:'1',jobName:'职位1'},
                {jobId:'2',jobName:'职位2'},*/
            ],
            showPageUserInfo:[    //当前页的员工信息
                /*{
                    key: '1',
                    userId: '1',
                    userAccount: '1',
                    username: 'John Brown',
                    password:'123',
                    deptName: '财务部',
                    jobName:'会计',
                    tel: 70,
                    status:'禁用',
                },
                {
                    key: '2',
                    userId: '2',
                    userAccount: '2',
                    username: 'Jim Green',
                    password:'123',
                    deptName: '营销部',
                    jobName:'销售',
                    tel: 89,
                    status:'启用',
                },
                {
                    key: '3',
                    userId: '3',
                    userAccount: '3',
                    username: 'Joe Black',
                    password:'123',
                    deptName: '财务部',
                    jobName:'会计',
                    tel: 70,
                    status:'启用',
                },
                {
                    key: '4',
                    userId: '4',
                    userAccount: '4',
                    username: 'Jim Red',
                    password:'123',
                    deptName: '财务部',
                    jobName:'会计',
                    tel: 89,
                    status:'启用',
                },
                {
                    key: '5',
                    userId: '5',
                    userAccount: '5',
                    username: 'John Brown',
                    password:'123',
                    deptName: '财务部',
                    jobName:'会计',
                    tel: 70,
                    status:'启用',
                },
                {
                    key: '6',
                    userId: '6',
                    userAccount: '6',
                    username: 'Jim Green',
                    password:'123',
                    deptName: '营销部',
                    jobName:'销售',
                    tel: 89,
                    status:'启用',
                },
                {
                    key: '7',
                    userId: '7',
                    userAccount: '7',
                    username: 'Joe Black',
                    password:'123',
                    deptName: '财务部',
                    jobName:'会计',
                    tel: 70,
                    status:'禁用',
                },
                {
                    key: '8',
                    userId: '8',
                    userAccount: '8',
                    username: 'Jim Red',
                    password:'123',
                    deptName: '财务部',
                    jobName:'会计',
                    tel: 89,
                    status:'启用',
                },*/
            ],
            thisState:'全部状态',    //当前选择的状态
            thisDept:'全部部门',    //当前选择的部门
            InfoModalVisible:false,     //员工信息模态框状态
            thisUserInfo:{     //员工信息模态框
                username :'',
                password:'',
                rePassword:'',
                userAccount:'',
                tel:'',
                deptName:'',
                jobName:'',
            },
            modalState:'add',    //员工信息模态框的用途（新增/修改），
            thisUrl:'',    //当前提交地址（新增/修改）
            postData:{},   //当前提交内容（新增/修改）
            name:'',    //当前提交显示文字（新增/修改）
            isOkVisible:false,    //提示模态框状态
            status:'',    //当前员工状态（启用/禁用）
            changeStatusVisible: false,    //确认启用/禁用模态框状态
        }
    }
    /*--------------------公用--------------------*/
    //改变state
    changeState=(name,value)=>{
        this.setState({
            [name]:value
        })
    };
    //发起请求，获取员工信息
    getStaffInfo=(postData)=>{
        // console.log(postData);
        axios({
            url:url.getStaffInfo,
            method:'post',
            data:postData,
        }).then(res=>{
            // console.log('获取员工信息');
            // console.log(res);
            if (res.data.code===200){
                // message.success('员工信息获取成功');
                let showUserInfo=[];
                res.data.data.userMsg.forEach(item=>{
                    // console.log(item);
                    let status;
                    item.status===0 ? status='启用' : status='禁用';
                    //再处理数据结构
                    showUserInfo.push({
                        key: item.userId,
                        userId: item.userId,
                        userAccount: item.userAccount,
                        username: item.username,
                        password: item.password,
                        deptName: item.dept[0].deptName,
                        jobName: item.job[0].jobName,
                        tel: item.tel,
                        status: status,
                    })
                });
                //将数据及总条数存入state
                this.changeState('showPageUserInfo',showUserInfo);
                this.changeState('totalCounts',res.data.data.count);
            }else {
                message.error('找到相应员工信息');
            }
        })
    };
    //发起请求，获取部门信息
    getDeptInfo=()=>{
        axios({
            url:url.showDeptInfo,
            method:'post',
            data:'',
        }).then(res=>{
            // console.log('获取部门信息');
            // console.log(res);
            if (res.data.code===200){
                // message.success('部门信息获取成功');
                //将数据存入state
                this.changeState('allDept',res.data.data);
            }else {
                message.error('部门信息获取失败');
            }
        })
    };
    //发起请求，获取职位信息
    getJobInfo=()=>{
        axios({
            url:url.getAllJob,
            method:'post',
            data:'',
        }).then(res=>{
            // console.log('获取职位信息');
            // console.log(res);
            if (res.data.code===200){
                // message.success('职位信息获取成功');
                //将数据存入state
                this.changeState('allJob',res.data.data);
            }else {
                message.error('职位信息获取失败');
            }
        })
    };
    /*--------------------信息确认弹窗--------------------*/
    //点击 信息提示 模态框确定
    toAjax=()=>{
        console.log(this.state.postData);
        let url=this.state.thisUrl+`?userAccount=${this.state.postData.userAccount}&&`+
            `username=${this.state.postData.username}&&deptName=${this.state.postData.deptName}&&`+
            `jobName=${this.state.postData.jobName}&&`+
            `password=${this.state.postData.password}&&`+
            `tel=${this.state.postData.tel}`;
        axios({
            url:url,
            method:'post',
            data:this.state.postData,
        }).then(res=>{
            // console.log(this.state.name);
            // console.log(res);
            if (res.data.code===200){
                message.success(`${this.state.name}成功`);
            }else {
                message.error(`${this.state.name}失败`);
            }
            this.changeState('isOkVisible',false);    //关闭信息提示弹窗
            this.changeState('InfoModalVisible',false);    //关闭填写信息弹窗
            this.getStaffInfo({currentPage:this.state.currentPage,perSize:this.state.perSize,});    //刷新列表
        });
    };
    //点击 信息提示 模态框中'取消'
    closeModal = e => {
        this.changeState('isOkVisible',false);
    };
    /*--------------------确认启用/禁用弹窗--------------------*/
    //点击 确认启用/禁用 模态框'确定'
    clickChangeStatus=()=>{
        let postData={userAccount:this.state.status.userAccount,status:''},text;
        this.state.status.status==='启用' ? postData.status= 1 : postData.status= 0;
        this.state.status.status==='启用' ? text= '禁用' : text= '启用';
        // console.log('修改状态传递的参数');
        // console.log(postData);
        axios({
            url:url.editUserStatus+`?status=${postData.status}&userAccount=${postData.userAccount}`,
            method:'post',
            data:postData,
        }).then(res=>{
            // console.log('修改状态返回');
            // console.log(res);
            if (res.data.code===200){
                message.success(`${text}成功`);
            }else {
                message.error(`${text}失败`);
            }
            this.changeState('changeStatusVisible',false);    //关闭弹窗
            this.getStaffInfo({currentPage:this.state.currentPage,perSize:this.state.perSize,});    //刷新列表
        });
    };
    //点击 确认启用/禁用 模态框中'取消'
    clickCloseModal = e => {
        this.changeState('changeStatusVisible',false);
    };
    /*--------------------搜索--------------------*/
    //渲染部门
    showDept=()=>{
        let dom=[];
        this.state.allDept.forEach(item=>{
            if(item.deptName==='根部门'){
                item.deptName='全部部门'
            }
            dom.push(<Menu.Item key={item.deptId}>{item.deptName}</Menu.Item>)
        });
        return dom;
    };
    //渲染状态
    showState=()=>{
        let dom=[];
        this.state.allState.forEach(item=>{
            dom.push(<Menu.Item key={item.key}>{item.name}</Menu.Item>)
        });
        return dom;
    };
    //点击下拉列表选择部门
    clickDept=(e)=>{
        this.state.allDept.forEach(item=>{
            if (e.key===item.deptId){
                this.changeState('thisDept',item.deptName)
            }
        });
    };
    //点击下拉列表选择状态
    clickState=(e)=>{
        this.state.allState.forEach(item=>{
            if (e.key===item.key){
                this.changeState('thisState',item.name)
            }
        });
    };
    //点击搜索
    searchUser=(value)=>{
        let postData={    //搜索条件
            currentPage:this.state.currentPage,    //当前页码
            perSize:this.state.perSize,    //页容量
        };
        this.changeState('currentPage',1);  //页码回到第一页
        if(this.state.thisDept!=='全部部门'){
            postData.selectValue = this.state.thisDept;    //部门
        }
        if(this.state.thisState!=='全部状态'){
            this.state.thisState==='启用' ? postData.selectValue1=0 :  postData.selectValue1=1;   //状态
        }
        if(value){
            postData.inputValue = value;     //输入框的值
        }
        // console.log('搜索条件');
        // console.log(postData);
        this.getStaffInfo(postData);     //获取 条件搜索 到的员工
    };
    /*--------------------新增--------------------*/
    //点击‘新增账号’
    addAccountBtn=()=>{
        this.changeState('thisUserInfo',{username :'', password:'', rePassword:'', userAccount:'', tel:'', deptName:'', jobName:'',});
        this.changeState('InfoModalVisible',true);
        this.changeState('modalState','add');   //模态框现在是新增
    };
    //点击 员工信息 模态框中'确认'
    handleOk = e => {
        //验证所有
        let mistakeNum=document.getElementsByClassName('ant-form-item-explain').length;   //验证不通过的个数
        let canSubMit=true;      //检查是否有输入框为空，判断是否可以提交
        for (let key in this.state.thisUserInfo){
            if (this.state.thisUserInfo[key]===''){
                canSubMit=false;
            }
        }
        if (mistakeNum<=0&&canSubMit){
            let postData={
                username :this.state.thisUserInfo.username,
                password:this.state.thisUserInfo.password,
                userAccount:this.state.thisUserInfo.userAccount,
                tel:this.state.thisUserInfo.tel,
                deptName:this.state.thisUserInfo.deptName,
                jobName:this.state.thisUserInfo.jobName,
            };
            let thisUrl,name;
            if (this.state.modalState==='add'){
                thisUrl=url.addUser;
                name='新增';
            }else {
                thisUrl=url.editUserInfo;
                name='修改';
            }
            this.changeState('postData',postData);
            this.changeState('thisUrl',thisUrl);
            this.changeState('name',name);
            this.changeState('isOkVisible',true);    //打开信息确认弹窗
        }
        else {
            message.error('请完善信息！');
        }
    };
    //点击 员工信息 模态框中'取消'
    handleCancel = e => {
        this.changeState('InfoModalVisible',false);
        this.changeState('thisUserInfo',{username :'', password:'', rePassword:'', userAccount:'', tel:'', deptName:'', jobName:'',});
    };
    //渲染部门下拉列表
    showDeptOption=()=>{
        let dom=[];
        // console.log(this.state.allDept);
        this.state.allDept.forEach(item=>{
            if(item.deptName!=='全部部门'){
                dom.push(<Option key={item.deptName}>{item.deptName}</Option>)
            }
        });
        return dom;
    };
    //渲染职位下拉列表
    showJobOption=()=>{
        let dom=[];
        this.state.allJob.forEach(item=>{
            dom.push(<Option key={item.jobName}>{item.jobName}</Option>)
        });
        return dom;
    };
    //输入框的值发生改变
    textChange=(itemName)=>{
        return (e)=>{
            let newUserInfo=Object.assign(this.state.thisUserInfo,{[itemName]:e.target.value});
            this.changeState('thisUserInfo',newUserInfo);
        }
    };
    //部门的下拉列表值改变
    depSelectChange=(value)=>{
      /*  console.log('部门');
        console.log(value);*/
        let newUserInfo=Object.assign(this.state.thisUserInfo,{deptName:value});
        this.changeState('thisUserInfo',newUserInfo);
    };
    //职位的下拉列表值改变
    jobSelectChange=(value)=>{
        /*console.log('职位');
        console.log(value);*/
        let newUserInfo=Object.assign(this.state.thisUserInfo,{jobName:value});
        this.changeState('thisUserInfo',newUserInfo);
    };
    /*--------------------表格内--------------------*/
    //渲染按钮
    dropdownMenu=(text, record)=>{
        const menu = (
            <Menu>
                <Menu.Item>
                    <a onClick={()=>this.editAccountBtn(text, record)}>
                        <EditOutlined  style={{color:'#13c19f',marginRight:'10px'}}/>修改
                    </a>
                    <a onClick={()=>this.changeStatus(record)}>
                        <MinusCircleOutlined style={{color:'#13c19f',marginRight:'10px'}}/>{this.btnText(record.status)}
                    </a>
                </Menu.Item>
            </Menu>
        );
        return(
            <Dropdown overlay={menu}>
                <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                    . . .
                </a>
            </Dropdown>
        )
    };
    //点击修改按钮
    editAccountBtn=(text,record)=>{
        let newInfo={...record};
        newInfo.rePassword=newInfo.password;
        this.changeState('thisUserInfo',newInfo);   //当前行数据
        this.changeState('modalState','edit');   //模态框现在是修改
        this.changeState('InfoModalVisible',true);
    };
    //判断按钮是启用还是禁用
    btnText=(status)=>{
        let text;
        status==='启用' ? text='禁用' : text='启用';
        return text;
    };
    //点击“禁用”/“启用”按钮
    changeStatus=(record)=>{
        this.changeState('status',record);    //保存当前员工用来修改状态
        this.changeState('changeStatusVisible',true);   //打开确认启用/禁用模态框
    };
    //点击页码
    pageChange=(page)=>{
        // console.log(page);
        this.changeState('currentPage',page);    //保存改变后的页码
        this.getStaffInfo({currentPage:this.state.currentPage,perSize:this.state.perSize});    //获取表格所需数据
    };
    render() {
        //部门下拉菜单
        const deptMenu =(
            <Menu onClick={this.clickDept}>
                {this.showDept()}
            </Menu>
        ) ;
        //状态下拉菜单
        const stateMenu = (
            <Menu onClick={this.clickState}>
                {this.showState()}
            </Menu>
        );
        //表格的字段
        const columns = [
            {title: '账号', dataIndex: 'userAccount', align:'center',},
            {title: '姓名', dataIndex: 'username', align:'center',},
            {title: '密码', dataIndex: 'password', align:'center',},
            {title: '部门', dataIndex: 'deptName', align:'center',},
            {title: '职位', dataIndex: 'jobName', align:'center',},
            {title: '手机', dataIndex: 'tel', align:'center',},
            {title: '状态', dataIndex: 'status', align:'center',},
            {title: '操作', key: 'action', align:'center', width:'80px',
                render: (text, record) => (
                    <span>
                        {this.dropdownMenu(text, record)}
                    </span>
                ),
            },
        ];
        return (
            <div className='DepAndStaffUserAccountPage'>
                <div className='hang1'>
                    {/*搜索部分*/}
                    <div className='searchBox'>
                        {/*部门下拉列表*/}
                        <Dropdown overlay={deptMenu} trigger={['click']}>
                            <div>
                                {this.state.thisDept} <DownOutlined />
                            </div>
                        </Dropdown>
                        {/*状态下拉列表*/}
                        <Dropdown overlay={stateMenu} trigger={['click']}>
                            <div>
                                {this.state.thisState} <DownOutlined />
                            </div>
                        </Dropdown>
                        {/*搜索输入框*/}
                        <Search placeholder="请输入员工姓名/账号/手机号/职位" onSearch={value => this.searchUser(value)} className='searchInput'/>
                    </div>
                    {/*新增部分*/}
                    <div className='addBtnBox'>
                        <Button type="primary" onClick={this.addAccountBtn}>新增账号</Button>
                    </div>
                </div>
                {/*表格展示*/}
                <Table columns={columns} dataSource={this.state.showPageUserInfo}
                       pagination={{
                           defaultCurrent:1,    //默认当前页
                           defaultPageSize:this.state.perSize,   //页容量
                           total:this.state.totalCounts,   //总条数
                           position:['bottomCenter'],   //页码位置
                           hideOnSinglePage:true,     //只有一页时隐藏分页
                           onChange:this.pageChange,    //页码发生改变时
                       }}
                />
                {/*新增账号模态框*/}
                <Modal
                    title="账号信息"
                    visible={this.state.InfoModalVisible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText='确认'
                    cancelText='取消'
                    getContainer={()=>document.getElementsByClassName('DepAndStaffUserAccountPage')[0]}
                    destroyOnClose={true}
                >
                    <Form name='addStaff' initialValues={this.state.thisUserInfo} size='middle' labelCol={{span:4,offset:2}} wrapperCol={{span: 16}}>
                        <Form.Item label="账号" name="userAccount" rules={[{required: true, message: '请输入账号!',},]}>
                            <Input onChange={this.textChange('userAccount')}  placeholder='请输入账号'/>
                        </Form.Item>
                        <Form.Item label="密码" name="password" rules={[{required: true, message: '请输入密码!',},]}>
                            <Input onChange={this.textChange('password')} placeholder='请输入密码'/>
                        </Form.Item>
                        <Form.Item label="确认密码" name="rePassword" rules={[
                            {required: true, message: '请输入再次密码!',},
                            ({ getFieldValue }) => ({
                                validator(rule, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject('密码输入不一致!');
                                },
                        }),]}>
                            <Input onChange={this.textChange('rePassword')} placeholder='请再次输入密码'/>
                        </Form.Item>
                        <Form.Item label="姓名" name="username" rules={[{required: true, message: '请输入姓名!',},]}>
                            <Input onChange={this.textChange('username')} placeholder='请输入姓名'/>
                        </Form.Item>
                        <Form.Item label="手机号" name="tel" rules={[{required: true, message: '请输入手机号!',},]}>
                            <Input onChange={this.textChange('tel')} placeholder='请输入手机号'/>
                        </Form.Item>
                        <Form.Item label="部门" name="deptName" rules={[{required: true, message: '请选择部门!',},]}>
                            <Select onChange={this.depSelectChange}>
                                {this.showDeptOption()}
                            </Select>
                        </Form.Item>
                        <Form.Item label="职位" name="jobName" rules={[{required: true, message: '请输入职位!',},]}>
                            <Select onChange={this.jobSelectChange}>
                                {this.showJobOption()}
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>
                {/*确认操作模态框*/}
                <Modal
                    title="提示"
                    visible={this.state.isOkVisible}
                    onOk={this.toAjax}
                    onCancel={this.closeModal}
                    okText="确认"
                    cancelText="取消"
                    getContainer={()=>document.getElementsByClassName('DepAndStaffUserAccountPage')[0]}
                >
                    <h1 style={{fontSize:'18px'}}>确认提交？</h1>
                </Modal>
                {/*确认启用/禁用模态框*/}
                <Modal
                    title="提示"
                    visible={this.state.changeStatusVisible}
                    onOk={this.clickChangeStatus}
                    onCancel={this.clickCloseModal}
                    okText="确认"
                    cancelText="取消"
                    getContainer={()=>document.getElementsByClassName('DepAndStaffUserAccountPage')[0]}
                >
                    <h1 style={{fontSize:'18px'}}>确认修改该员工状态？</h1>
                </Modal>
            </div>
        );

    };
    componentDidMount() {
        //获取当前页员工信息
        this.getStaffInfo({currentPage:this.state.currentPage,perSize:this.state.perSize});
        //获取部门信息
        this.getDeptInfo();
        //获取职位信息
        this.getJobInfo();
    }
}

export default DepAndStaffUserAccount;